package cn.wolfcode.crm.web.advice;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice//针对所有控制器所有控制方法,出了异常都能处理
public class ExceptionHandlerControllerAdvice {

    @ExceptionHandler(Exception.class)
    public ModelAndView handlerException(Exception e, HandlerMethod method, Model model){
        e.printStackTrace();
        return getModelAndView(e, method, "common/error", e.getMessage());
    }


    @ExceptionHandler(UnauthorizedException.class)
    public ModelAndView handlerUnauthorizedException(Exception e, HandlerMethod method, Model model){
        e.printStackTrace();
        return getModelAndView(e, method, "common/nopermission", "你没有该权限");
    }

    private ModelAndView getModelAndView(Exception e, HandlerMethod method, String viewName, String message) {
        ResponseBody responseBodyAnno = method.getMethodAnnotation(ResponseBody.class);
        if (responseBodyAnno == null) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName(viewName);
            mv.addObject("ex", e);
            return mv;
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("msg", message);
            ModelAndView mv = new ModelAndView(new MappingJackson2JsonView(), map);
            return mv;
        }
    }

}
